<template>
  <div id="app">
    <router-view/>
    <AddPanel ref="AddPanel"/>
    <el-button @click="addPanel" type="primary">添加Panel</el-button>
    <el-button @click="checkFormat" type="primary">检查格式</el-button>
    <div :style="wrapSty" class="wrap">
      <canvas id="canvas"></canvas>
      <div id="b6-map-scatter" class="map-chart-b6" :style="wrapSty"></div>
      <div class="center"></div>
      <div class="top-line">{{ wrapWidth }}</div>
      <div class="left-line">{{ wrapHeight }}</div>
    </div>
  </div>
</template>

<script>
import {fabric} from 'fabric'
import json from '../data.json'
import * as echarts from 'echarts'
import AddPanel from "../AddPanel.vue";
import layoutMixin from "../layout.mixin.js"
import {qPanelData, fucks} from '../chartData.js'

export default {
  components: {
    AddPanel,
  },
  computed: {
    wrapSty() {
      return {
        width: this.wrapWidth + 'px',
        height: this.wrapHeight + 'px',
        transform: 'scale(1)'
      }
    }
  },
  mixins: [layoutMixin],
  data() {
    let qData = json.data.records.find(it => it.id === 25)
    return {
      wrapWidth: 0,
      wrapHeight: 0,
      myChart: null,
      qPanelData
    }
  },
  mounted() {
    // function resizeCanvas() {
    //   const container = document.getElementById('canvas-wrapper')
    //   const scaleX = container.clientWidth / originalWidth
    //   const scaleY = container.clientHeight / originalHeight
    //   const scale = Math.min(scaleX, scaleY) // 保持比例
    //
    //   canvas.setWidth(originalWidth * scale)
    //   canvas.setHeight(originalHeight * scale)
    //
    //   canvas.setZoom(scale)  // 缩放内容
    // }
    //
    // window.addEventListener('resize', resizeCanvas)
    // resizeCanvas()

    this.setChartsOptions()
    //  this.myChart?.setOption?.({ graphic: this.getDimensionLines() });
    //  this.setChartPanelInfoSimple()
    this.setLayout()
  },
  methods: {
    checkFormat() {
      let {qpanelInfos} = qPanelData
      let bigQErrX = qpanelInfos.filter(it => it.topLeftX < it.bottomRightX).map(it => it.panelId).join(',')
      let bigQErrY = qpanelInfos.filter(it => it.topLeftY > it.bottomRightY).map(it => it.panelId).join(',')

      if (bigQErrX) {
        this.$message.error(`Q-Panel【${bigQErrX}】的左上角x坐标必须小于右下角x坐标`)
        return false
      }
      if (bigQErrY) {
        this.$message.error(`Q-Panel【${bigQErrY}】的左上角y坐标必须大于右下角y坐标`)
        return false
      }
      let allSmallPanel = qpanelInfos.map(it => it.panelInfos).flat()
      let smallErrX = allSmallPanel.filter(it => it.topLeftX < it.bottomRightX).map(it => it.panelId).join(',')
      let smallErrY = allSmallPanel.filter(it => it.topLeftY > it.bottomRightY).map(it => it.panelId).join(',')
      if (smallErrX) {
        this.$message.error(`Panel【${smallErrX}】的左上角x坐标必须小于右下角x坐标`)
        return false
      }
      if (smallErrY) {
        this.$message.error(`Panel【${smallErrY}】的左上角y坐标必须大于右下角y坐标`)
        return false
      }
      return true

    },

    setChartPanelInfoSimple() {
      const gridComponent = this.myChart.getModel().getComponent('grid');
      const {width, height, x, y} = gridComponent.coordinateSystem.getRect();
      // this.layoutInfo.left = x
      // this.layoutInfo.top = y
      // this.layoutInfo.width = width
      // this.layoutInfo.height = height
    },
    addPanel() {
      this.$refs.AddPanel.show()
    },
    drawCanvasBorder(canvas, options = {}) {
      const stroke = options.strokeWidth ?? 1;
      const color = options.color ?? 'black';

      // 让左/上从整像素开始，宽高减去 stroke，保证完全落在画布里
      const borderRect = new fabric.Rect({
        left: 0,
        top: 0,
        width: canvas.width - stroke,
        height: canvas.height - stroke,
        stroke: color,
        strokeWidth: stroke,
        fill: 'transparent',
      });

      canvas.add(borderRect);


      return borderRect;
    },
    setLayout() {
      let {totalWidth, totalHeight, qpanelInfos} = this.qPanelData || fucks
      this.wrapWidth = totalWidth
      this.wrapHeight = totalHeight

      const canvas = new fabric.StaticCanvas('canvas', {
        width: totalWidth, // 画布宽度
        height: totalHeight, // 画布高度
        backgroundColor: 'white', // 画布背景色
      })
      canvas.renderOnAddRemove = false // 关闭自动
      let objectsToAdd = []
      for (let it of qpanelInfos) {
        for (let it2 of it.panelInfos) {
          objectsToAdd.push(this.setRectTxtGroup(it2, totalWidth, totalHeight))
        }
        objectsToAdd.push(this.setRectTxtGroup(it, totalWidth, totalHeight, true))
      }
      canvas.add(...objectsToAdd)
    },
    setRectTxtGroup(it, totalWidth, totalHeight, isQ = false) {//大Q降低不透明度，扩大字体100px
      let {topLeftX, topLeftY, bottomRightX, bottomRightY, panelId} = it
      let width = Math.abs(bottomRightX - topLeftX)
      let height = Math.abs(bottomRightY - topLeftY)

      // 1. 限制字体大小的逻辑
      const minDim = Math.min(width, height);
      let calculatedFontSize =  minDim * 0.5;//为Q时，缩放0.8倍，为panel时，缩小一半
      let scaleList=[{len:3,scale:0.8},{len:4,scale:0.7},{len:5,scale:0.6},{len:6,scale:0.5},{len:7,scale:0.4},{len:8,scale:0.3},{len:9,scale:0.3},{len:10,scale:0.3}]
      if(panelId.length>2){
        let scaleItem=scaleList.find(item=>item.len===panelId.length)
        calculatedFontSize=calculatedFontSize*scaleItem.scale
      }
      let rect = new fabric.Rect({
        width,
        height,
        fill: 'white',
        stroke: isQ ? 'red' : 'black',        // 边框颜色
        strokeWidth: 1,
        originX: 'center',
        originY: 'center',
      })
      const text = new fabric.Text(panelId, {
        fontSize: calculatedFontSize,
        fill: '#000',
        originX: 'center',
        originY: 'center',
      })

      return new fabric.Group([rect, text], {
        left: totalWidth / 2 + topLeftX,
        top: totalHeight / 2 - topLeftY,
        originX: 'left',
        originY: 'top',
        opacity: isQ ? 0.2 : 1,
      })
    },
    setChartsOptions() {
      let {totalWidth, totalHeight, qpanelInfos} = this.qPanelData
      this.wrapWidth = totalWidth
      this.wrapHeight = totalHeight
      let option = {
        grid: {
          left: 0,
          top: 0,
          right: 0,
          bottom: 0
        },
        tooltip: {
          trigger: 'item',
          formatter: function (params) {
            return `x: ${params.data[0]}, y: ${params.data[1]}`;
          }
        },
        xAxis: {
          min: -totalWidth / 2,
          max: totalWidth / 2,
          interval: 2,
          show: false,
          type: 'value',
          splitLine: {show: false},
          axisLine: {show: true, onZero: false},
          axisTick: {show: false},
          axisLabel: {show: false},
        },
        yAxis: {
          min: -totalHeight / 2,
          max: totalHeight / 2,
          interval: 2,
          show: false,
          type: 'value',
          splitLine: {show: false},
          axisLine: {show: true, onZero: false},
          axisTick: {show: false},
          axisLabel: {show: false},
        },
        series: [
          {
            type: 'scatter',
            data: [[0, 0], [-100, -100], [100, 100], [50, 50], [600, 619], [128, 176], [724, 421]],
            // symbolSize: 5
          }
        ]
      };
      this.$nextTick(_ => {
        this.myChart = echarts.init(document.getElementById('b6-map-scatter'));
        this.myChart.setOption(option);
      })
    },
    setRectTxtGroup1(it, totalWidth, totalHeight, isQ = false) {//大Q降低不透明度，扩大字体100px
      let {topLeftX, topLeftY, bottomRightX, bottomRightY, panelId} = it
      let width = Math.abs(bottomRightX - topLeftX)
      let height = Math.abs(bottomRightY - topLeftY)
      let rect = new fabric.Rect({
        width,
        height,
        fill: 'white',
        stroke: isQ ? '' : 'black',        // 边框颜色
        strokeWidth: 1,
        originX: 'center',
        originY: 'center',
      })
      const text = new fabric.Text(panelId, {
        fontSize: isQ ? 100 : 14,
        fill: '#000',
        originX: 'center',
        originY: 'top',
        top: -height / 2
      })

      let rect1 = new fabric.Rect({
        width: width * 0.3,
        height: height / 3,
        fill: '#B7DAFE',
        opacity: 1,
        strokeWidth: 1,
        originX: 'center',
        originY: 'bottom',
        top: height / 2
      })
      const text1 = new fabric.Text('0.5%', {
        fontSize: 14,
        fill: '#000',
        originX: 'center',
        originY: 'bottom',
        top: height / 2
      })
      return new fabric.Group([rect, text, rect1, text1], {
        left: totalWidth / 2 + topLeftX,
        top: totalHeight / 2 - topLeftY,
        originX: 'left',
        originY: 'top',
        opacity: isQ ? 0.2 : 1,
        subTargetCheck: true,
      })
    },
    setLayout1() {
      let {totalWidth, totalHeight, qpanelInfos} = qPanelData
      this.wrapWidth = totalWidth
      this.wrapHeight = totalHeight

      const canvas = new fabric.StaticCanvas('canvas', {
        width: totalWidth, // 画布宽度
        height: totalHeight, // 画布高度
        backgroundColor: 'white', // 画布背景色
      })
      canvas.renderOnAddRemove = false // 关闭自动
      let objectsToAdd = []
      for (let it of qpanelInfos) {
        for (let it2 of it.panelInfos) {
          objectsToAdd.push(this.setRectTxtGroup(it2, totalWidth, totalHeight))
        }
        objectsToAdd.push(this.setRectTxtGroup(it, totalWidth, totalHeight, true))
      }
      canvas.add(...objectsToAdd)
    },
  }
}
</script>
<style lang="stylus">
.center {
  width 5px
  height 5px
  text-align center
  border-radius 100%
  background red
  left 50%
  position absolute;
  top: 50%
  transform translate(-50% -50%)
}

.wrap {
  margin: 10px auto
  position: relative
  box-shadow: 0 0 0 0.5px black
  border 1px solid red;
}

.map-chart-b6 {
  position: absolute;
  top: 0;
  left: 0;
  border 1px solid green;

}

.top-line, .left-line {
  position absolute
  text-align center
  font-weight bold
}

.top-line {
  top -20px
  left 50%
  transform translateX(-50%)
}

.left-line {
  top 50%
  transform rotateZ(-90deg)
  left -25px
}

.testPoint {
  position absolute;
  width 15px;
  height 15px;
  background red;
  left 600px
  top 619px
  //  "topLeftX": 600.482,
  //"topLeftY": 619.57,
  //"bottomRightX": 724.31,
  //"bottomRightY": 421.43
}
</style>